package com.huarui.employee.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.exception.BizException;
import org.ewaf.framework.model.ListModel;
import org.ewaf.framework.util.HttpUtil;
import com.huarui.company.model.Company;
import com.huarui.company.service.CompanyService;
import com.huarui.department.service.DepartmentService;
import com.huarui.employee.model.AddingEmployee;
import com.huarui.employee.model.Employee;
import com.huarui.employee.model.EmployeeListModel;
import com.huarui.employee.model.HireHistory;
import com.huarui.employee.service.AddingEmployeeService;
import com.huarui.employee.service.EmployeeService;
import com.huarui.employee.service.HireHistoryService;
import com.huarui.user.error.UserError;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.model.User;
import com.huarui.user.security.UserHolder;
import com.huarui.user.service.UserService;
import com.huarui.util.JsonUtil;
/**
 * xzz
 * 
 * @author Administrator
 * 
 */
public class EmployeeAction extends BaseAction {
	private static final long serialVersionUID = 1332350149304984690L;
	private String activateCode;
	private String password;
	private String email;
	private String companyName;
	private EmployeeService employeeService;
	private UserService userService;
	private CompanyService companyService;
	private User user;
	private Company company;
	private Employee employee;
	private HireHistory hireHistory;
	private HireHistoryService hireHistoryService;
	private SessionMessage sessionMessage;
	private List<Employee> employeeList;
	private DepartmentService departmentService;
	private List<HireHistory> hireHistoryList;
	private String dir;
	private String sort;
	private int start;
	private int limit;
	private ListModel<Employee> listModel;
	private String eid;
	Map<String, Object> resultMap = new HashMap<String, Object>();
	private AddingEmployeeService  addingEmployeeService;

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getCompanyName() {
		return companyName;
	}

	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}

	public AddingEmployeeService getAddingEmployeeService() {
		return addingEmployeeService;
	}

	public void setAddingEmployeeService(AddingEmployeeService addingEmployeeService) {
		this.addingEmployeeService = addingEmployeeService;
	}

	public String getActivateCode() {
		return activateCode;
	}

	public void setActivateCode(String activateCode) {
		this.activateCode = activateCode;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Map<String, Object> getResultMap() {
		return resultMap;
	}

	public String getEid() {
		return eid;
	}

	public void setEid(String eid) {
		this.eid = eid;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public ListModel<Employee> getListModel() {
		return listModel;
	}

	public void setListModel(ListModel<Employee> listModel) {
		this.listModel = listModel;
	}
	public DepartmentService getDepartmentService() {
		return departmentService;
	}

	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}

	public List<Employee> getEmployeeList() {
		return employeeList;
	}

	public void setEmployeeList(List<Employee> employeeList) {
		this.employeeList = employeeList;
	}

	public SessionMessage getSessionMessage() {
		return sessionMessage;
	}

	public void setSessionMessage(SessionMessage sessionMessage) {
		this.sessionMessage = sessionMessage;
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public void setCompany(Company company) {
		this.company = company;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public void setHireHistory(HireHistory hireHistory) {
		this.hireHistory = hireHistory;
	}

	public void setHireHistoryService(HireHistoryService hireHistoryService) {
		this.hireHistoryService = hireHistoryService;
	}

	public User getUser() {
		return user;
	}

	public Company getCompany() {
		return company;
	}

	public Employee getEmployee(){
		return employee;
	}

	public HireHistory getHireHistory() {
		return hireHistory;
	}

	public List<HireHistory> getHireHistoryList() {
		return hireHistoryList;
	}

	public void setHireHistoryList(List<HireHistory> hireHistoryList) {
		this.hireHistoryList = hireHistoryList;
	}

	/**
	 * 邀请员工加入公司
	 * 
	 * @return
	 */
	public String addEmp() {
        
		if(StringUtils.isBlank(activateCode)){
			
			throw new RuntimeException("您好!您所使用的安全码已经过期,您可以请求该公司重新发送邀请");
		}
		
	    AddingEmployee addingEmployee = addingEmployeeService.getByActivateCode(activateCode);
	    
	    if(addingEmployee==null){
	    	
	    	throw new RuntimeException("您好!您已经成为该公司的员工,不能重复加入");
	    }
	    
        email=addingEmployee.getAddeeEmail();
        companyName=addingEmployee.getCompanyName();
		try {
			employeeService.addEmployee(addingEmployee);

		} catch (Exception e) {
//            e.printStackTrace();
			throw new RuntimeException(e.getMessage(),e);
		}

		return "success";

	}

	/**
	 * 员工离开公司
	 * 
	 * @return
	 */
	public String leaveCompany() {

		HttpServletRequest request = HttpUtil.getRequest();

		String evaluation = request.getParameter("evaluation");

		sessionMessage = UserHolder.getCurrentSessionMessage();

		user = (User) userService.getById(sessionMessage.getUserId());

		user.setCompanyId(0);

		employee = employeeService.getEmployeeByUserId(user.getId(), user
				.getCompanyId(),0);

		employee.setIsDelete(1);

		employee.setIncumbent(false);

		hireHistory = hireHistoryService.getHireHistoryByGmt(user.getId(),
				employee.getGmtCreate());

		hireHistory.setType(1);

		hireHistory.setEvaluation(evaluation);

		employeeService.update(employee);

		hireHistoryService.update(hireHistory);

		userService.update(user);

		return SUCCESS;

	}

	public String index() {

		sessionMessage = UserHolder.getCurrentSessionMessage();

		return "index";

	}

	/**
	 * 编辑员工信息
	 * 
	 * @return
	 * @throws IOException
	 */
	public String query() throws IOException {
		sessionMessage = UserHolder.getCurrentSessionMessage();
		EmployeeListModel lm = getModelUtil(httpServletRequest);

		// user为公司的创建者
		user = (User) userService.getById(sessionMessage.getUserId());
		// employeeList是公司里的所有员工
		try {
			listModel = employeeService.getEmployeeByCompanyId(user.getCompanyId(),lm);
		} catch (Exception e) {
			
			e.printStackTrace();
		}

		JSONArray root = JSONArray.fromObject(listModel.getResult());

		// 分页信息
		resultMap.put("totalProperty", listModel.getTotal());
		resultMap.put("page", lm.getPage());
		resultMap.put("root", root);

		return "json";
	}

	@SuppressWarnings("unchecked")
	public String update() throws IOException {

		HttpServletRequest request = HttpUtil.getRequest();

		String jsonAll = request.getParameter("jsonAll");

		JSONObject jsonObject = JSONObject.fromObject(jsonAll);

		Map map = new HashMap();
		
		try {
		  
		  Employee employee =  JsonUtil.getBean(jsonObject,
					Employee.class);
          
          map.put("companyId",employee.getCompanyId());
          map.put("code",employee.getCode());
          Employee employee1 = employeeService.getEmployeeByCodeAndCompanyId(map);

          if(employee1!=null){
        	  
        	  if(!employee1.getId().equals(employee.getId())){
        		resultMap.put("failure", "该员工工号已被使用");

    			return "json";
        	  }
          }
          
          Map<String, Object> hashMap = employeeService.modifyEmployee(employee);   
          

            if(hashMap.containsKey("already_be_modify")){			

				resultMap.put("failure",hashMap.get("already_be_modify"));
				return "json";
		   }
		} catch (Exception e) {
			
			resultMap.put("failure", "更新员工失败");

			return "json";

		}

		resultMap.put("success", "OK");
		return "json";
	}

	public String delete() throws IOException {

		HttpServletRequest request = ServletActionContext.getRequest();

		String employeeId = request.getParameter("id");

		String evaluation = request.getParameter("evaluation");

		if (StringUtils.isBlank(employeeId)) {

			resultMap
					.put("failure", UserError.EMPLOYEE_NOT_EXSIT.getChError());

			return "json";

		}

		try {
			Employee employee = (Employee) employeeService.getById(Integer
					.valueOf(employeeId));

			Integer companyId = employee.getCompanyId();

			Company company = (Company) companyService.getById(companyId);
					
			if (employee.getUserId() == company.getCreatorId()) {

				resultMap.put("failure", UserError.NO_RIGHT_DELETE_THE_EMPLOYEE
						.getChError());

				return "json";

			}
			
			employeeService.deleteEmployee(employee,company,evaluation);
			
		} catch (Exception e) {

			resultMap.put("failure", "删除员工失败");

			return "json";
		}

		return null;

	}
/**public String index_HireHistory() {
		HttpServletRequest request = HttpUtil.getRequest();

		eid = request.getParameter("id");

		return "index";
	}*/

	public String browseHireHistory() throws IOException {

		HttpServletRequest request = HttpUtil.getRequest();

		sessionMessage = UserHolder.getCurrentSessionMessage();

		ListModel<HireHistory> lm = new ListModel<HireHistory>();
		lm.setPageSize(limit);
		lm.setPage(start);
		lm.setOrderBy(sort);
		lm.setDesc(dir.equals("desc") ? true : false);

		String id = request.getParameter("id");

		if (StringUtils.isBlank(id)) {

			throw new BizException(UserError.EMPLOYEE_NOT_EXSIT);

		}
		Integer employeeId = Integer.valueOf(id);

		employee = (Employee) employeeService.getById(employeeId);

		ListModel<HireHistory> listModel = hireHistoryService.getByUserId(employee.getUserId(), lm);

		JSONArray root = JSONArray.fromObject(listModel.getResult());

		// 分页信息
		resultMap.put("totalProperty", listModel.getTotal());
		resultMap.put("page", lm.getPage());
		resultMap.put("root", root);

		return "json";
	}
	
	private EmployeeListModel getModelUtil(HttpServletRequest request) {
		
		EmployeeListModel employeeListModel=new EmployeeListModel();
		employeeListModel.setPageSize(limit);
		employeeListModel.setStart(start);
		employeeListModel.setOrderBy(sort);
		employeeListModel.setDesc(dir.equalsIgnoreCase("desc") ? true : false);
		String jsonAll = request.getParameter("jsonAll");
		
		if (StringUtils.isNotBlank(jsonAll)) {

			JSONObject jsonObject = JSONObject.fromObject(jsonAll);
			
			employeeListModel.setIsDelete(jsonObject.getString("isDelete"));
			
		}
				
		return employeeListModel;
	}
}
